package boot.spring.controller;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RLongAdder;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import boot.spring.po.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "分布式锁")
@RestController
@RequestMapping("/lock")
public class LockController {

    @Autowired
    RedissonClient redissonClient;

    @ApiOperation("可重入锁")
    @GetMapping("/reentrantLock")
    public  AjaxResult reentrantLock() throws Exception {
        RLongAdder longAddr = redissonClient.getLongAdder("longAddr");
        RLock lock = redissonClient.getLock("reentrantLock");
        // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
        boolean res;
        res = lock.tryLock(100, 10, TimeUnit.SECONDS);
        if (res) {
            try {
                longAddr.add(1);
                longAddr.add(3);
            } finally {
                lock.unlock();
            }
        }
        return AjaxResult.success(longAddr.sum());
    }
}
